<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

function list_user_friendiness($uid, $weights, $start = 0, $limit = 0) {
    $query = DB::query("SELECT count(*) * $weights as friendliness, p1.uid, m.username
        FROM ".DB::table('yydjourney_participants')." p1
        INNER JOIN ".DB::table('yydjourney_participants')." p2 on p1.jid = p2.jid and p2.uid = $uid
        INNER JOIN ".DB::table("common_member")." m on m.uid = p1.uid
        JOIN ".DB::table('yydjourneys')." j on j.id = p1.jid
        where p1.uid <> $uid AND j.finished = 1
        GROUP BY p1.uid ORDER BY friendliness DESC ".DB::limit($start, $limit));

    $friends = array();
    while($result = DB::fetch($query)) {
        $result['avatar'] = avatar($result['uid'], 'small');
        $friends[] = $result;
    }
    return $friends;
}

function rank_global_friendiness($weights, $start = 0, $limit = 0) {
    $query = DB::query("SELECT count(*) * $weights as friendliness, 
        p1.uid as uid1, m1.username as username1, p2.uid as uid2, m2.username as username2
        FROM ".DB::table('yydjourney_participants')." p1
        JOIN ".DB::table('yydjourney_participants')." p2 on p1.jid = p2.jid and p1.uid < p2.uid
        JOIN ".DB::table("common_member")." m1 on m1.uid = p1.uid
        JOIN ".DB::table("common_member")." m2 on m2.uid = p2.uid
        JOIN ".DB::table('yydjourneys')." j on j.id = p1.jid
        WHERE j.finished = 1
        GROUP BY p1.uid, p2.uid
        ORDER BY friendliness DESC ".DB::limit($start, $limit));
    
    $ranks = array();
    while($result = DB::fetch($query)) {
        $result['avatar1'] = avatar($result['uid1'], 'small');
        $result['avatar2'] = avatar($result['uid2'], 'small');
        $ranks[] = $result;
    }
    return $ranks;
}
